package com.sri.system;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sri.cache.CacheManager;
import com.sri.db.dao.BeanManager;
import com.sri.lucene.index.IndexManager;

/**
 * @author skodali
 * 
 */
public class RentalInitServlet extends HttpServlet {

	/**
 * 
 */
	public RentalInitServlet() {
		// TODO Auto-generated constructor stub
	}

	public void init() {
		initRentalSchedulers();
		initApplicationContext();
		initCache();
		initIndex();
		initSouts();
		initLog4j();
	}

	private void initIndex() {
		try {
			System.out.println("Indexing.......");
			IndexManager.rebuildIndexes();
			System.out.println("Indexing....... Completed");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Initializes the Rental Applications Requirements
	 */
	protected void service(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {

	}

	/**
	 * Initializes the Log4J configuration
	 * 
	 */
	protected void initLog4j() {
		System.out.println("init Log4J");
		String prefix = getServletContext().getRealPath("/");
		String suffix = getInitParameter("log4j");
		PropertyConfigurator.configure(prefix + suffix);

	}

	/**
	 * Initialize the Rental Shedulers
	 * 
	 */
	protected void initRentalSchedulers() {

	}

	protected void initSouts() {
		try {
			PrintStream stream = new PrintStream(new FileOutputStream(
					"..//logs//rental.log"));
			System.setOut(stream);
			System.setErr(stream);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	protected void initApplicationContext() {
		BeanManager.setContext(new ClassPathXmlApplicationContext(
				"conf/applicationContext.xml"));
	}

	public void distroy() {
	}

	protected void initCache() {
		CacheManager cache = new CacheManager(getServletContext());
		cache.cleanApplicationData();
		cache.getStates();
		cache.getCities();

	}

}
